package org.simple.framework.boot.config;

import com.fasterxml.classmate.TypeResolver;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Pageable;
import springfox.documentation.schema.AlternateTypeRule;
import springfox.documentation.schema.AlternateTypeRuleConvention;

import java.security.Principal;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static springfox.documentation.schema.AlternateTypeRules.newRule;

/**
 * 项目名称：simple-framework
 * 类名称：SimpleAlternateTypeRuleConvention
 * 类描述：优化swagger自动生成的api doc
 * 创建时间：2018/8/14
 *
 * @author sisyphus   (E-mail:1620657419@qq.com)
 * @version v1.0
 */
@Configuration
@ConditionalOnBean({TypeResolver.class})
public class SimpleAlternateTypeRuleConvention implements AlternateTypeRuleConvention {

    @Autowired(required = false)
    private TypeResolver resolver;

    @Override
    public List<AlternateTypeRule> rules() {
        if (resolver == null) {
            return Collections.emptyList();
        }
        return Arrays.asList(
                newRule(resolver.resolve(Pageable.class), resolver.resolve(Page.class)),
                newRule(resolver.resolve(Principal.class), resolver.resolve(Empty.class)));
    }

    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE;
    }

    @Data
    private static class Page {

        @ApiModelProperty("第几页 (0..N)")
        private Integer page;

        @ApiModelProperty("每页记录数")
        private Integer size;

        @ApiModelProperty("排序相关的信息，以property,property(,ASC|DESC)的方式组织，例如sort=firstname&sort=lastname,desc表示在按firstname正序排列基础上按lastname倒序排列。")
        private List<String> sort;

    }

    @Data
    private static class Empty {

    }

}
